<!--
  对账详情组件
  @description 查看对账单的详细信息和差异明细
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1200px"
    :scroll="true"
    max-height="700px"
  >
    <div v-loading="loading">
      <!-- 对账基本信息 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('settle.reconciliation.basicInfo') }}</span>
          </div>
        </template>
        <el-descriptions :column="3" border v-if="reconciliationData">
          <el-descriptions-item :label="t('settle.reconciliation.reconciliationNo')">
            {{ reconciliationData.reconciliationNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.reconciliationDate')">
            {{ reconciliationData.reconciliationDate }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.merchantNo')">
            {{ reconciliationData.merchantNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.merchantName')">
            {{ reconciliationData.merchantName }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.channelType')">
            <el-tag :type="getChannelTypeTagType(reconciliationData.channelType)">
              {{ channelTypeOptions[reconciliationData.channelType] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.reconciliationStatus')">
            <el-tag :type="getReconciliationStatusTagType(reconciliationData.reconciliationStatus)">
              {{ reconciliationStatusOptions[reconciliationData.reconciliationStatus] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.totalCount')">
            {{ reconciliationData.totalCount }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.totalAmount')">
            <span class="amount-text"
              >¥{{ (reconciliationData.totalAmount / 100).toFixed(2) }}</span
            >
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.diffCount')">
            <span :class="reconciliationData.diffCount > 0 ? 'diff-text' : ''">
              {{ reconciliationData.diffCount }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.reconciliation.diffAmount')">
            <span :class="reconciliationData.diffAmount !== 0 ? 'diff-text' : ''">
              ¥{{ (reconciliationData.diffAmount / 100).toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.common.createTime')">
            {{ formatDate(reconciliationData.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.common.updateTime')">
            {{ formatDate(reconciliationData.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 差异明细 -->
      <el-card v-if="reconciliationData?.diffCount && reconciliationData.diffCount > 0">
        <template #header>
          <div class="card-header">
            <span>{{ t('settle.reconciliation.diffDetails') }}</span>
            <el-button
              type="primary"
              size="small"
              @click="handleRefreshDiff"
              :loading="diffLoading"
            >
              <Icon class="mr-5px" icon="ep:refresh" />
              {{ t('settle.common.refresh') }}
            </el-button>
          </div>
        </template>

        <!-- 差异搜索 -->
        <el-form
          ref="diffQueryFormRef"
          :model="diffQueryParams"
          :inline="true"
          label-width="80px"
          class="mb-20px"
        >
          <el-form-item :label="t('settle.reconciliation.diffType')" prop="diffType">
            <el-select
              v-model="diffQueryParams.diffType"
              :placeholder="t('settle.common.pleaseSelect') + t('settle.reconciliation.diffType')"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="(label, value) in diffTypeOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('settle.reconciliation.orderNo')" prop="orderNo">
            <el-input
              v-model="diffQueryParams.orderNo"
              :placeholder="t('settle.common.pleaseInput') + t('settle.reconciliation.orderNo')"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleDiffQuery">
              <Icon class="mr-5px" icon="ep:search" />
              {{ t('settle.common.search') }}
            </el-button>
            <el-button @click="resetDiffQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              {{ t('settle.common.reset') }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 差异列表 -->
        <el-table :data="diffList" row-key="id" v-loading="diffLoading">
          <el-table-column
            :label="t('settle.reconciliation.orderNo')"
            align="center"
            prop="orderNo"
            width="200"
          />
          <el-table-column
            :label="t('settle.reconciliation.diffType')"
            align="center"
            prop="diffType"
            width="120"
          >
            <template #default="scope">
              <el-tag :type="getDiffTypeTagType(scope.row.diffType)">
                {{ diffTypeOptions[scope.row.diffType] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.reconciliation.ourAmount')"
            align="center"
            prop="ourAmount"
            width="120"
          >
            <template #default="scope"> ¥{{ (scope.row.ourAmount / 100).toFixed(2) }} </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.reconciliation.channelAmount')"
            align="center"
            prop="channelAmount"
            width="120"
          >
            <template #default="scope">
              ¥{{ (scope.row.channelAmount / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.reconciliation.diffAmount')"
            align="center"
            prop="diffAmount"
            width="120"
          >
            <template #default="scope">
              <span class="diff-text"> ¥{{ (scope.row.diffAmount / 100).toFixed(2) }} </span>
            </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.reconciliation.diffReason')"
            align="center"
            prop="diffReason"
            min-width="200"
          />
          <el-table-column
            :label="t('settle.reconciliation.handleStatus')"
            align="center"
            prop="handleStatus"
            width="100"
          >
            <template #default="scope">
              <el-tag :type="getHandleStatusTagType(scope.row.handleStatus)">
                {{ handleStatusOptions[scope.row.handleStatus] }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 差异分页 -->
        <Pagination
          :total="diffTotal"
          v-model:page="diffQueryParams.pageNo"
          v-model:limit="diffQueryParams.pageSize"
          @pagination="getDiffList"
          class="mt-20px"
        />
      </el-card>

      <!-- 无差异提示 -->
      <el-card v-else-if="reconciliationData && reconciliationData.diffCount === 0">
        <el-empty :description="t('settle.reconciliation.noDiff')" />
      </el-card>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'
import { getReconciliationFileApi, getReconciliationDiffPageApi } from '@/api/settle/reconciliation'
import type {
  ReconciliationVO,
  ReconciliationDiffVO,
  ReconciliationDiffPageReqVO
} from '@/api/settle/types'
import {
  ReconciliationStatusEnum,
  ChannelTypeEnum,
  DiffTypeEnum,
  HandleStatusEnum
} from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'

defineOptions({ name: 'ReconciliationDetail' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)
const diffLoading = ref(false)

// 对账数据
const reconciliationData = ref<ReconciliationVO>()

// 差异列表数据
const diffList = ref<ReconciliationDiffVO[]>([])
const diffTotal = ref(0)

// 差异查询参数
const diffQueryParams = reactive<ReconciliationDiffPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  reconciliationId: 0,
  diffType: undefined,
  orderNo: undefined
})

// 表单引用
const diffQueryFormRef = ref<FormInstance>()

// 选项数据
const channelTypeOptions = {
  [ChannelTypeEnum.WECHAT]: t('settle.reconciliation.channelTypes.wechat'),
  [ChannelTypeEnum.ALIPAY]: t('settle.reconciliation.channelTypes.alipay'),
  [ChannelTypeEnum.UNIONPAY]: t('settle.reconciliation.channelTypes.unionpay'),
  [ChannelTypeEnum.DIGITAL_RMB]: t('settle.reconciliation.channelTypes.digitalRmb')
}

const reconciliationStatusOptions = {
  [ReconciliationStatusEnum.PENDING]: t('settle.reconciliation.reconciliationStatuses.pending'),
  [ReconciliationStatusEnum.SUCCESS]: t('settle.reconciliation.reconciliationStatuses.success'),
  [ReconciliationStatusEnum.FAILED]: t('settle.reconciliation.reconciliationStatuses.failed'),
  [ReconciliationStatusEnum.PROCESSING]: t(
    'settle.reconciliation.reconciliationStatuses.processing'
  )
}

const diffTypeOptions = {
  [DiffTypeEnum.AMOUNT_DIFF]: t('settle.reconciliation.diffTypes.amountDiff'),
  [DiffTypeEnum.STATUS_DIFF]: t('settle.reconciliation.diffTypes.statusDiff'),
  [DiffTypeEnum.MISSING_ORDER]: t('settle.reconciliation.diffTypes.missingOrder'),
  [DiffTypeEnum.EXTRA_ORDER]: t('settle.reconciliation.diffTypes.extraOrder')
}

const handleStatusOptions = {
  [HandleStatusEnum.PENDING]: t('settle.reconciliation.handleStatuses.pending'),
  [HandleStatusEnum.HANDLED]: t('settle.reconciliation.handleStatuses.handled'),
  [HandleStatusEnum.IGNORED]: t('settle.reconciliation.handleStatuses.ignored')
}

/**
 * 打开对话框
 */
const open = async (reconciliation: ReconciliationVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('settle.reconciliation.detail') + ' - ' + reconciliation.reconciliationNo
  loading.value = true

  try {
    // 获取对账详情
    const data = await getReconciliationFileApi(reconciliation.id)
    reconciliationData.value = data

    // 如果有差异，加载差异列表
    if (data.diffCount > 0) {
      diffQueryParams.reconciliationId = data.id
      await getDiffList()
    }
  } catch (error) {
    console.error('获取对账详情失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 获取差异列表
 */
const getDiffList = async () => {
  diffLoading.value = true
  try {
    const data = await getReconciliationDiffPageApi(diffQueryParams)
    diffList.value = data.list
    diffTotal.value = data.total
  } catch (error) {
    console.error('获取差异列表失败:', error)
  } finally {
    diffLoading.value = false
  }
}

/**
 * 刷新差异数据
 */
const handleRefreshDiff = () => {
  getDiffList()
}

/**
 * 差异搜索
 */
const handleDiffQuery = () => {
  diffQueryParams.pageNo = 1
  getDiffList()
}

/**
 * 重置差异搜索
 */
const resetDiffQuery = () => {
  diffQueryParams.diffType = undefined
  diffQueryParams.orderNo = undefined
  diffQueryFormRef.value?.resetFields()
  handleDiffQuery()
}

// 标签类型获取函数
const getChannelTypeTagType = (type: number) => {
  const typeMap = {
    [ChannelTypeEnum.WECHAT]: 'success',
    [ChannelTypeEnum.ALIPAY]: 'primary',
    [ChannelTypeEnum.UNIONPAY]: 'warning',
    [ChannelTypeEnum.DIGITAL_RMB]: 'info'
  }
  return typeMap[type] || ''
}

const getReconciliationStatusTagType = (status: number) => {
  const statusMap = {
    [ReconciliationStatusEnum.PENDING]: 'info',
    [ReconciliationStatusEnum.PROCESSING]: 'warning',
    [ReconciliationStatusEnum.SUCCESS]: 'success',
    [ReconciliationStatusEnum.FAILED]: 'danger'
  }
  return statusMap[status] || ''
}

const getDiffTypeTagType = (type: number) => {
  const typeMap = {
    [DiffTypeEnum.AMOUNT_DIFF]: 'warning',
    [DiffTypeEnum.STATUS_DIFF]: 'info',
    [DiffTypeEnum.MISSING_ORDER]: 'danger',
    [DiffTypeEnum.EXTRA_ORDER]: 'primary'
  }
  return typeMap[type] || ''
}

const getHandleStatusTagType = (status: number) => {
  const statusMap = {
    [HandleStatusEnum.PENDING]: 'warning',
    [HandleStatusEnum.HANDLED]: 'success',
    [HandleStatusEnum.IGNORED]: 'info'
  }
  return statusMap[status] || ''
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.mt-20px {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-text {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.diff-text {
  color: #f56c6c;
  font-weight: bold;
}
</style>
